#!/usr/bin/env python3
"""
Ed25519密钥对生成器
用于生成和风天气API JWT认证所需的Ed25519密钥对
"""

import os
import hashlib
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ed25519


def generate_ed25519_keypair():
    """生成Ed25519密钥对"""
    # 生成私钥
    private_key = ed25519.Ed25519PrivateKey.generate()
    
    # 从私钥获取公钥
    public_key = private_key.public_key()
    
    return private_key, public_key


def save_private_key(private_key, filename="ed25519-private.pem"):
    """保存私钥到PEM文件"""
    private_pem = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption()
    )
    
    with open(filename, 'wb') as f:
        f.write(private_pem)
    
    return private_pem


def save_public_key(public_key, filename="ed25519-public.pem"):
    """保存公钥到PEM文件"""
    public_pem = public_key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo
    )
    
    with open(filename, 'wb') as f:
        f.write(public_pem)
    
    return public_pem


def calculate_sha256(data):
    """计算数据的SHA256哈希值"""
    return hashlib.sha256(data).hexdigest()


def main():
    """主函数"""
    print("正在生成Ed25519密钥对...")
    
    # 生成密钥对
    private_key, public_key = generate_ed25519_keypair()
    
    # 保存私钥
    private_pem = save_private_key(private_key)
    print(f"✓ 私钥已保存到: ed25519-private.pem")
    
    # 保存公钥
    public_pem = save_public_key(public_key)
    print(f"✓ 公钥已保存到: ed25519-public.pem")
    
    # 计算公钥的SHA256哈希值
    public_sha256 = calculate_sha256(public_pem)
    
    print("\n" + "="*60)
    print("密钥生成完成！")
    print("="*60)
    
    print(f"\n私钥文件: ed25519-private.pem")
    print("⚠️  请妥善保管私钥，不要泄露给他人！")
    
    print(f"\n公钥文件: ed25519-public.pem")
    print("📤 需要将公钥内容上传到和风天气控制台")
    
    print(f"\n公钥SHA256哈希值:")
    print(f"{public_sha256}")
    print("💡 可用此哈希值在控制台验证公钥是否正确")
    
    print(f"\n公钥内容:")
    print("-" * 40)
    print(public_pem.decode('utf-8'))
    print("-" * 40)
    
    print("\n使用说明:")
    print("1. 复制上面的公钥内容（包括BEGIN和END行）")
    print("2. 登录和风天气控制台 -> 项目管理")
    print("3. 选择项目 -> 添加凭据 -> JSON Web Token")
    print("4. 粘贴公钥内容并保存")
    print("5. 验证控制台显示的SHA256值与上面的哈希值是否一致")


if __name__ == "__main__":
    try:
        main()
    except ImportError as e:
        print("❌ 缺少必要的依赖库！")
        print("请运行以下命令安装依赖:")
        print("pip install cryptography")
        print(f"\n错误详情: {e}")
    except Exception as e:
        print(f"❌ 生成密钥时发生错误: {e}") 